package com.zhht.htzx.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.binding_state.BR;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.ToastUtils;
import com.zhht.htzx.R;
import com.zhht.htzx.utils.QRCodeScannerUtils;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class QRCodeScannerActivity extends BaseActivity {
    private static final int PERMISSION_REQUEST_CODE = 100;
    private static final int GALLERY_REQUEST_CODE = 200;
    private static final String[] REQUIRED_PERMISSIONS = {Manifest.permission.CAMERA};

    private PreviewView previewView;
    private View scanFrame;
    private View scanLine;
    private TextView tvScanTip;
    private ImageView btnBack;
    private FloatingActionButton btnFlashlight;
    private FloatingActionButton btnGallery;
    private ExecutorService cameraExecutor;
    private boolean isFlashOn = false;
    private boolean isScanning = false;

    private AccountRequester mAccountRequester;
    private StateHolder mStates;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_qr_code_scanner, BR.vm, mStates);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        initViews();
        initListeners();
        startScanLineAnimation();

        if (allPermissionsGranted()) {
            startCamera();
        } else {
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE);
        }

        cameraExecutor = Executors.newSingleThreadExecutor();

        mAccountRequester.getSrcSuccess().observe(this, new Observer<ResponseStatus<String>>() {
            @Override
            public void onChanged(ResponseStatus<String> stringResponseStatus) {
                if (stringResponseStatus.getResponseCode()==0){
                    ToastUtils.showShortToast("核销成功");
                    finish();
                }
            }
        });
    }

    private void initViews() {
        previewView = findViewById(R.id.preview_view);
        scanFrame = findViewById(R.id.scan_frame);
        scanLine = findViewById(R.id.scan_line);
        tvScanTip = findViewById(R.id.tv_scan_tip);
        btnBack = findViewById(R.id.btn_back);
        btnFlashlight = findViewById(R.id.btn_flashlight);
        btnGallery = findViewById(R.id.btn_gallery);
    }

    private void initListeners() {
        btnBack.setOnClickListener(v -> finish());
        btnFlashlight.setOnClickListener(v -> toggleFlashlight());
        btnGallery.setOnClickListener(v -> openGallery());
    }

    private void startScanLineAnimation() {
        // 创建扫码线上下移动动画
        TranslateAnimation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0f,
                Animation.RELATIVE_TO_PARENT, 0f,
                Animation.RELATIVE_TO_PARENT, 0f,
                Animation.RELATIVE_TO_PARENT, 0.95f
        );
        animation.setDuration(2000);
        animation.setRepeatCount(Animation.INFINITE);
        animation.setRepeatMode(Animation.REVERSE);
        scanLine.startAnimation(animation);
    }

    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture =
                ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider);
            } catch (ExecutionException | InterruptedException e) {
                Toast.makeText(this, "启动相机失败", Toast.LENGTH_SHORT).show();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
        Preview preview = new Preview.Builder().build();
        preview.setSurfaceProvider(previewView.getSurfaceProvider());

        ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                .build();

        imageAnalysis.setAnalyzer(cameraExecutor, this::analyzeImage);

        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                .build();

        try {
            cameraProvider.unbindAll();
            cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);
        } catch (Exception e) {
            Toast.makeText(this, "绑定相机失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void analyzeImage(@NonNull androidx.camera.core.ImageProxy image) {
        if (isScanning) {
            image.close();
            return;
        }

        // 使用工具类识别二维码
        String result = QRCodeScannerUtils.scanQRCodeFromImageProxy(image);

        if (result != null && !result.trim().isEmpty()) {
            isScanning = true;
            runOnUiThread(() -> handleScanResult(result));
        }

        image.close();
    }

    private void handleScanResult(String result) {
        // 停止扫码线动画
        scanLine.clearAnimation();

        // 显示扫描结果
//        Toast.makeText(this, "扫描成功: " + result, Toast.LENGTH_LONG).show();

        // 处理不同类型的扫描结果
        if (QRCodeScannerUtils.isValidUrl(result)) {
            // 如果是URL，检查是否为邀请链接
            String inviteCode = QRCodeScannerUtils.extractInviteCode(result);
            if (inviteCode != null) {
                handleInviteCode(inviteCode);
            } else {
                handleUrl(result);
            }
        } else {
            // 普通文本
            handleText(result);
        }

        // 返回扫描结果
//        Intent intent = new Intent();
//        intent.putExtra("scan_result", result);
//        setResult(RESULT_OK, intent);
//        finish();
    }

    private void handleInviteCode(String inviteCode) {
        Toast.makeText(this, "检测到邀请码: " + inviteCode, Toast.LENGTH_SHORT).show();
        // 这里可以跳转到邀请注册页面
    }

    private void handleUrl(String url) {
        Toast.makeText(this, "检测到链接: " + url, Toast.LENGTH_SHORT).show();
        // 这里可以打开浏览器或应用内WebView
    }

    private void handleText(String text) {
        // 这里可以处理普通文本内容
        mAccountRequester.verificationSheet(text);
    }

    private void toggleFlashlight() {
        // 切换闪光灯状态
        isFlashOn = !isFlashOn;
        btnFlashlight.setImageResource(isFlashOn ?
                android.R.drawable.ic_menu_camera : android.R.drawable.ic_menu_view);

        // 这里需要实现闪光灯控制逻辑
        Toast.makeText(this, isFlashOn ? "闪光灯已开启" : "闪光灯已关闭", Toast.LENGTH_SHORT).show();
    }

    private void openGallery() {
        // 打开相册选择图片进行二维码识别
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, GALLERY_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                // 从相册图片中识别二维码
                String result = QRCodeScannerUtils.scanQRCodeFromImageUri(this, imageUri);
                if (result != null && !result.trim().isEmpty()) {
                    handleScanResult(result);
                } else {
                    Toast.makeText(this, "未在图片中检测到二维码", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private boolean allPermissionsGranted() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (allPermissionsGranted()) {
                startCamera();
            } else {
                Toast.makeText(this, "需要相机权限才能使用扫码功能", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cameraExecutor != null) {
            cameraExecutor.shutdown();
        }
        // 停止动画
        if (scanLine != null) {
            scanLine.clearAnimation();
        }
    }
} 